import Foundation
import Security
import UIKit

class KeyChainForUUID: NSObject {
    
    // 生成 UUID
    private static func generateUUID() -> String {
        return UUID().uuidString
    }
    
    // 存储到 Keychain
    private static func saveUUIDToKeychain(uuid: String, key: String) -> Bool {
        let keychainItem: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: key,
            kSecAttrAccount: key,
            kSecValueData: uuid.data(using: .utf8)!
        ]
        
        // 先删除已存在的条目（如果有）
        let deleteStatus = SecItemDelete(keychainItem as CFDictionary)
        if deleteStatus != errSecSuccess && deleteStatus != errSecItemNotFound {
            return false
        }
        
        // 添加新条目
        let status = SecItemAdd(keychainItem as CFDictionary, nil)
        return status == errSecSuccess
    }
    
    // 从 Keychain 读取 UUID
    private static func getUUIDFromKeychain(key: String) -> String? {
        let query: [CFString: Any] = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: key,
            kSecAttrAccount: key,
            kSecReturnData: kCFBooleanTrue!,
            kSecMatchLimit: kSecMatchLimitOne
        ]
        
        var data: AnyObject?
        let status = SecItemCopyMatching(query as CFDictionary, &data)
        
        if status == errSecSuccess, let data = data as? Data {
            return String(data: data, encoding: .utf8)
        }
        return nil
    }
    
    // 获取设备唯一标识符 (UUID + Keychain)
    class func getDeviceUUID() -> String {
        let key = "com.example.app.deviceUUID" // 替换为你的应用标识
        if let uuid = getUUIDFromKeychain(key: key) {
            return uuid
        } else {
            let newUUID = generateUUID()
            let _ = saveUUIDToKeychain(uuid: newUUID, key: key)
            return newUUID
        }
    }
}
    
